
package com.baidu.ai.aip.auth;

import com.alibaba.fastjson.JSON;
import com.baidu.ai.aip.auth.HttpUtil;
import com.baidu.ai.aip.auth.GsonUtils;
import com.google.gson.JsonObject;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.*;

/**
 * 在线图片活体v3
 */
public class FaceVerify {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String faceVerify(String value) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
        try {
            Map map =new HashMap();
            map.put("image",value);
            map.put("image_type","BASE64");
            map.put("face_field","age,beauty,spoofing");
            map.put("option","COMMON");
            String param = GsonUtils.toJson(map);
            param="["+param+"]";
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();;
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        String value=Base64Util.encode(FileUtil.readFileByBytes("C:\\Users\\ly\\IdeaProjects\\Tyust_face\\img\\photo\\91c7a502c0a84b9ea42cd2f74cc8d561.jpg"));
        String result=FaceVerify.faceVerify(value);
        System.out.println("---------");
        HashMap hashMap=JSON.parseObject(result,HashMap.class);
        result=hashMap.get("result").toString();
        hashMap=JSON.parseObject(result,HashMap.class);
        System.out.println(hashMap.get("face_liveness"));

    }
}